package controllers

import (
	"strings"
	"mailsrv/models"
	"github.com/astaxie/beego"
)

type MainController struct {
	BaseController
}


func (this *MainController) Get() {
	welcomePage := this.URLFor("MainController.Welcome")
	this.Redirect(welcomePage, 302)
}

func (this *MainController) Prepare(){
	this.BaseController.Prepare()
}



func (this *MainController) Welcome(){
	this.setTpl("welcome.html")
}

func (this *MainController) Home(){

	this.setTpl("home.html")
}


/*
应用接入管理
 */
 func (this *MainController) AppsList(){
	 this.setTpl("apps.html")
 }
func (this *MainController) AppsListApi(){
	page, _ := this.GetInt("page")
	appReps := models.Apps{}
	datas, total := appReps.PageList(page)
	this.pageApiJson(datas, total, "", 0)
}


func (this *MainController)AppsInsert(){
	mailsrv := models.MailerSrv{}
	allmails := mailsrv.AllMails()

	beego.Notice(allmails)

	this.Data["allmails"] = allmails
	this.setTpl("apps_insert.html")
 }

 func (this *MainController)AppsDelDo(){
	 id, _ := this.GetInt("id")
	 if id==0{
		 this.goError("ID丢失！")
	 }

	 apps := models.Apps{}
	 _, err := apps.AppsDel(id)

	 if err != nil {
		 this.ajaxReturn("", "删除失败", 400)
	 }else{
		 this.ajaxReturn("", "成功", 200)
	 }
 }



func (this *MainController)AppsEdit(){
	id, _ := this.GetInt("id")
	if id==0{
		this.goError("ID丢失！")
	}
	model := models.Apps{}
	info, _ := model.GetOne(id)

	mailsrv := models.MailerSrv{}
	allmails := mailsrv.AllMails()

	this.Data["allmails"] = allmails
	this.Data["info"] = info
	this.setTpl("apps_edit.html")
}

func (this *MainController)AppsInsertDo(){
	name := strings.TrimSpace(this.GetString("name"))
	appid := strings.TrimSpace(this.GetString("appid"))
	appkey := strings.TrimSpace(this.GetString("appkey"))
	desc := strings.TrimSpace(this.GetString("desc"))
	mid,_ := this.GetInt("mid")

	if len(appid) < 5 {
		this.ajaxReturn("", "APPID 不能小于5个字符", 400)
	}

	params := models.Apps{
		Mid:mid,
		Name:name,
		Appid:appid,
		Appkey:appkey,
		Desc:desc,
	}

	result := params.AppsInsert()
	if result != nil {
		error_msg := result.Error()
		this.ajaxReturn("", "添加失败："+error_msg, 400)
	}else{
		this.ajaxReturn(map[string]string{"url":this.URLFor("MainController.AppsList")}, "成功", 200)
	}
}


func (this *MainController)AppsEditDo(){
	id, _ := this.GetInt("id")
	if id==0{
		this.ajaxReturn("", "ID丢失", 400)
	}
	name := strings.TrimSpace(this.GetString("name"))
	appid := strings.TrimSpace(this.GetString("appid"))
	appkey := strings.TrimSpace(this.GetString("appkey"))
	desc := strings.TrimSpace(this.GetString("desc"))
	mid,_ := this.GetInt("mid")

	params := models.Apps{
		Id:id,
		Mid:mid,
		Name:name,
		Appid:appid,
		Appkey:appkey,
		Desc:desc,
	}


	result, _ := params.AppsEdit()

	if result <= 0 {
		this.ajaxReturn("", "失败", 400)
	}else{
		this.ajaxReturn(map[string]string{"url":this.URLFor("MainController.AppsList")}, "成功", 200)
	}
}

